<template>
	<div class="table">
		<div class="table-header" v-if="selectedKeys?.length">
			<div class="table-number" >
				已勾选{{ selectedKeys.length }}项 <span @click="selectedKeys = []" class="table-btn" style="color: #165dff;"> 取消选择</span>
			</div>
			<div>
				<span :class="['table-btn' ,{'disable':selectedKeys.length > 1}]" :style="{ color: item.color }" :disabled="selectedKeys.length > 1"  type="text" @click="handleBtn(item.type)" v-for="(item,index) in btnList" :key="index">
					<i :class="['EachApp', item.icon]"></i>
					{{item.label}}
				</span>
			</div>
		</div>
		<div class="table-tabs" v-else>
			<a-radio-group v-model="deptIndex" type="button" @change="handleBtn('tabs', $event)">
				<a-radio :value="item.value" v-for="item in ORG_TYPE" :key="item.value">{{ item.label }}</a-radio>
			</a-radio-group>
			<div class="right flex">
				<template v-if="searchTag.keys">
					{{ searchTag.title }}搜索:
					<a-tag color="arcoblue" closable @close="handleBtn('clearTag')" class="small-tag">{{ searchTag.keys }}</a-tag>
				</template>
				<ComSearch :isIcon="false" @handleSearch="handleBtn('search', $event)" width="300px" ref="comSearchRef"></ComSearch>
			</div>
		</div>
		<!-- {{ currentRowInfo }}---{{ computedUser() ? 'nickname' : 'name' }}--{{ changeType }} -->
		<div class="table-list">
			<a-table ref="tableRef" body-cell-class="table-cell" :loading="loading" :data="dataList" row-key="id" :row-selection="{type: 'radio', showCheckedAll: true, onlyCurrent: false,}" :columns="columns" :pagination="false" @row-click="handleRow"
			@cell-click="handleCell" @cell-mouse-enter="handleCellEnter" @cell-mouse-leave="handleCellLeave" @selection-change="selectChange" :selectedKeys="selectedKeys" :hoverable="false" >
				<template #nickname="{ record, rowIndex }" >
					<div style="display: flex; height: 30px;"  @keyup.enter="handleSubmit($event, 'mobile', false)"   v-if="record.isHover|| record.isEdit">
						<a-input-group  >
							<a-input :style="{width:'50px'}" placeholder="姓氏"  v-model.trim="record.firstName "  @keyup.enter="handleSubmit($event, 'mobile', false)" maxlength="1"/>
							<a-input :style="{width:'120px'}" placeholder="名字" v-model.trim="record.lastName"  @keyup.enter="handleSubmit($event, 'mobile', false)" maxlength="3"/>
						</a-input-group>
					</div>
					<div v-else style="width: 169px;">
						<ComAvatar :url="record.avatar?record.avatar:''" :name="record.initialLetter" :sex="record.sex" :size="22"/>
						{{ record.nickname }}
					</div>
				</template>
				<template #deptNames="{ record }">
					<span :class="{ 'common-area': record.deptNames?.length }"><i>{{ computedPinYin(record.deptNames?.toString()) }}</i> {{ record.deptNames?.toString() }}</span>
				</template>
				<template #postNames="{ record }">
					<span :class="{ 'common-area': record.postNames?.length }"><i>{{ computedPinYin(record.postNames?.toString()) }}</i> {{ record.postNames?.toString() }}</span>
				</template>
				<template #depts="{ record }">
					<span :class="{ 'common-area': record.depts?.length }"><i>{{ computedPinYin(record.depts?.map(item => { return item.name }).toString()) }}</i> {{ record.depts?.map(item => { return item.name }).toString() }}</span>
				</template>
				<template #mobile="{ record }">
					<a-input v-model.trim="record.mobile" @keyup.enter="handleSubmit($event, 'mobile', false)" :class="iptClass(record)" maxlength="11"></a-input>
				</template>
				<template #email="{ record }">
					<a-input v-model.trim="record.email" @keyup.enter="handleSubmit($event, 'email', false)" :class="iptClass(record)"></a-input>
				</template>
				<template #totalUser="{ record ,rowIndex}">
					<span class="hover" @click="handleBtn('checkUser', record)">{{ record.totalUser }}</span>
				</template>
				<template #status="{ record }">
					<a-tag :color="record.status === 0 ? 'arcoblue' : 'red'">{{ (deptIndex === 'dept' ? RESIGN_STATUS : POST_STATUS).find(item => item.value === record.status)?.label }}</a-tag>
				</template>
			</a-table>
			<ComPage v-model:total="total" v-model:limit="pageParams.pageSize" @pagination="getList"
				v-model:page="pageParams.pageNo" />
		</div>
	</div>
	<ComModal v-model:modalVisible="modalVisible" :title="changeTitle" submitText="提交" @handleCancel="modalVisible = false" @handleSubmit="myComponentRef?.handleSubmit" scroll-to-first-error width="500px">
		<component :userId="selectedKeys" :changeType="changeType" :is="myComponent" ref="myComponentRef" :currentNode="currentNodeInfo" @refreshList="handleBtn('refreshList')"></component>
	</ComModal>
	 <!-- 选择部门、岗位 -->
	 <!-- computedUser() ? postUserList : currentNodeInfo.deptList -->
	 <!-- computedUser() ? 'nickname' : 'name' -->
	 <!-- currentRowInfo?.userIds -->
    <ChangeDeptPost ref="changeDeptPostRef" :title="changeTitle" :postList="currentNodeInfo.postList" @send-list="sendList" :multiple="!['transfer', 'deptManager'].includes(changeType)"
		:list="treeList" :params="treeParams" :checkedList="currentRowInfo?.deptIds" :filterList="treeFilter" :treeType="currentNodeInfo.isDept ? 'dept' : 'post'"/>
</template>
<script lang="ts" setup>
// import AddUser  from './AddUser.vue';
import * as Api from '@/api/common';
import mitt from '@/utils/bus';
import mixins from '@/mixins/index.js';
import { isSame } from "@/utils/index";
import { POST_STATUS, ORG_TYPE, RESIGN_STATUS } from "@/utils/filter";
import pinyin from 'js-pinyin';
import { deptColumns, postColumns, deptBtns, postBtns } from './filter';

const Add = defineAsyncComponent(() => import('./Add.vue'));
const AddUser = defineAsyncComponent(() => import('./AddUser.vue'));
const UserForm = defineAsyncComponent(() => import('./UserForm.vue'));
const { handleMixinSubmit, handleMixinFocus, handleMixinBlur ,message} = mixins();
const dataList = ref([]); // 用户列表
const dataListInit = ref([]); // 用户列表
const currentRow = ref({}); // 鼠标移入当前行
const changeTitle = ref(''); // 弹出名称
// const message = useMessage();
const changeType=ref();
const myComponent=ref();
const myComponentRef=ref();
const modalVisible=ref(false);
const changeDeptPostRef = ref();
const tableRef  = ref(null);
const currentRowInfo = ref(null); // 当前行信息 
const currentRowIndex = ref(-1); // 当前行index 
const currentNodeInfo = ref({});
const loading=ref(false);//加载状态
const selectedKeys=ref([]);//已选择的数据
const postUserList = ref([]); // 岗位下的人员
const postUserListAll = ref([]); // 岗位下的人员
const treeList = ref([]);
const treeParams = ref('');
const treeFilter = ref([]);
const iptClass = computed(() => (record) => {
    return [!record.isEdit ? 'edit-fields-normal' : 'edit-fields-focus'];
})
const comSearchRef = ref(null);
const injectCheckUser = inject(['checkUser']);
const injectIsChecked = inject('isChecked');
const columns = ref([]);
const btnList = ref([]);//按钮列表
const total = ref(0);
const deptIndex = ref('dept');
const searchTag = ref({
	key: '',
	title: ''
});
const pageParams=reactive({
	pageNo:1,
	pageSize:10,
	searchKey: '', // 关键字
	postId:null,
	deptId:null
})

// 是否操作成员
const computedUser = computed(() => () => {
	return ['delUser', 'addUser'].includes(changeType.value);
})

watch(() => currentNodeInfo.value, e => {
	treeList.value = e?.isDept ? e?.deptList: postUserListAll.value;
	treeParams.value = e?.isDept ? 'name' : 'nickname';
	columns.value = e?.isDept ? deptColumns : postColumns;
	btnList.value = e?.isDept ? deptBtns : postBtns;
}, { deep: true })


watch(() => selectedKeys.value, e => {
	if(e.length){
		currentRowInfo.value = dataList.value.find(item => item.id === e[0]);
		const { status } = currentRowInfo.value;
		const { isDept } = currentNodeInfo.value;
		console.log('status===', status, isDept);
		if(isDept){
			// 处理部门 0在职  1离职
			if(status === 0){
				btnList.value = deptBtns.filter(item => !['back'].includes(item.type));
			}else{
				btnList.value = deptBtns.filter(item => !['leave', 'deptManager', 'transfer'].includes(item.type));
			}
		}else{
			// 处理部门 0启用 1停用
			if(status === 0){
				btnList.value = postBtns.filter(item => !['enable'].includes(item.type));
			}else{
				btnList.value = postBtns.filter(item => !['disable', 'delUser', 'addUser'].includes(item.type));
			}
		}
	}
})

// 获取用户列表
const getList = async () => {
	try{
		
		loading.value = true;
		let https = currentNodeInfo?.value?.isDept ? Api.ApiUserPage : Api.ApiPostPage;
		const res = await https(pageParams);
		dataList.value = res?.list.map(item=>{
			item.isHover=false;
			return item
		});
		total.value = res?.total || 0;
		// console.log('dataList.value===', dataList.value);
		dataListInit.value =  JSON.parse(JSON.stringify(dataList?.value || []))
		injectIsChecked(true);
	}catch(err){console.log(err);}finally{
		loading.value = false;
		selectedKeys.value = [];
		currentRowInfo.value = {};
		changeType.value = '';
	}
}
// 获取岗位的人员
const getPostUser = async () => {
	try{;
		const res = await Api.ApiUserList();
		postUserListAll.value = res || [];
	}catch(err){console.log(err);}
}
// 点击行
const handleRow = (row) => {
	const rowIndex = dataListInit.value.findIndex(item => item.id === row.id);
	dataList.value.map((item) => {
		return (item.isEdit = item.id === row.id);
	});
	if (currentRowIndex.value!== rowIndex) {
		if(currentRowIndex.value > -1){
			handleSubmit();
		}
		currentRowIndex.value = rowIndex;
	}
}
// 点击单元格
const handleCell=(record,column)=>{
	currentRow.value=record;
	
};
// 鼠标进入单元格
const handleCellEnter=(record,column)=>{
	record.isHover = column.dataIndex == 'nickname' ? true : false;
	
}
// 鼠标离开单元格
const handleCellLeave=(record)=>{
	dataList.value.map(item => {
		return item.isHover = false;
	})
	// handleSubmit()
}
// 选择行发生改变
const  selectChange=(rowKeys)=>{
	selectedKeys.value=rowKeys;
}
// 鼠标离开
const handleBlur = async (row, keys) => {
	dataList.value.map(item => {
		return item.isEdit = false;
	})
	// await handleMixinBlur(Api.ApiUpdateRow, row, currentRow.value, "", dataList.value, keys);
	// emit("refreshList");
};
const handleSubmit = async (event, keys, isEmpty = false) => {
        if(event){
            event.target.blur();
            if(!isEmpty && !event?.target.value){
                currentRow.value = {};
                return message.warning('该值不能为空，请重新填写!');
            }
        }
        if(currentRow.value?.id){
            // 找到原数据
            const oldRow = dataListInit.value.find(item => item.id === currentRow.value.id);
            // 是否修改过
			if(!oldRow || !currentRow.value) return;
            const same = isSame(oldRow, currentRow.value, "isEdit");
            // console.log('oldRow===', {...oldRow});
            // console.log('newRow===', {...currentRow.value});
            // console.log('isUpdate===', same);
            if(!same){
                try{
					currentRow.value.deptId = currentRow.value.deptIds?.toString();
                    await handleMixinSubmit(Api.ApiUserUpdate, currentRow.value, getList, false);
                    currentRow.value = {};
                    getList();
                }finally{
                    currentRowIndex.value = -1;
                }
            }
            dataList.value.map(item => { return item.isEdit = false });
        }
    }
// 选择部门、岗位
const handleAdd = ( type) => {
	let array = dataList.value.find(t=>t.id==selectedKeys.value[0]);

	if (type === 'dept') {
		changeDeptPostRef.value.deptCheckedIds = array?.deptIds;
		
	} else {
		// changeDeptPostRef.value.deptCheckedIds = []
		changeDeptPostRef.value.postListNew.forEach((k) => {
			array.postIds?.forEach((z) => {
				if (k.id === z) {
					k.checked = true
					const index = changeDeptPostRef.value.postChecked.findIndex((i) => i.id === k.id)
					if (index === -1) {
						changeDeptPostRef.value.postChecked.push(k)
					}
				}
			})
		})
	}
	changeTitle.value = type
	changeDeptPostRef.value.modalVisible = true ; 
}
// 修改部门,岗位,设置部门负责人
const sendList=async(e)=>{
	console.log('e====', e);
	if(e.length==0 && !computedUser.value){
		message.warning(`请选择${changeType.value=='post' ? '岗位' : '部门'}`);
		return
	}
	const { id, isDept } = currentNodeInfo.value;
	if(['dept','post'].includes(changeType.value)){
		let info = dataList.value.find(t=>t.id==selectedKeys.value[0]);
		if(changeType.value=='dept'){
			info.deptIds=e.map(item=>item.id)
		}else {
			info.postIds = e.map(item=>item.id)
		}
		await handleMixinSubmit(Api.ApiUserUpdate, info,getList, false);
	}else if(changeType.value=='deptManager'){
		const { id } = e[0];
		const params={
		   userId:selectedKeys.value[0]
        };
		Api.ApiManager(id, params).then(res => {
			mitt.emit('getTree');
			getList();
		}).catch((err) => {
			console.log(err);
		})
	}else if(changeType.value === 'transfer'){
		const { id, name, parentId } = e[0];
		const params = {
			id: currentRowInfo.value.id,
			deptId: id,
	    }
		await handleMixinSubmit(Api.ApiUserChangeDept, params, getList, false);
	}else if(['delUser'].includes(changeType.value)){
		const params = {
			userIds: changeDeptPostRef.value.deptCheckedIds?.toString(),
			postId: currentRowInfo.value.id,
		}
		console.log('移除====', {...params});
		await handleMixinSubmit(Api.ApiUserPostRemove, params, getList, false);
		changeDeptPostRef.value.treeRef.treeList = [];
	}else if(['addUser'].includes(changeType.value)){
		const params = {
			userIds: changeDeptPostRef.value.deptCheckedIds,
			postId: currentRowInfo.value.id,
			deptId: currentNodeInfo.value.id
		}
		// console.log('添加====', {...params});
		await handleMixinSubmit(Api.ApiUserPostAdd, params, getList, false);
	}
	changeDeptPostRef.value.modalVisible = false;
	changeType.value = '';
}
const handleBtn = async (type, value) => {
	changeType.value = type;
	const { isDept } = currentNodeInfo.value;
	const { id, name, remark, status, deptIds, leaderDeptIds } = currentRowInfo?.value;
	// console.log('按钮===', type, isDept);
	if(type=='add'){
		console.log('deptIndex.value===', deptIndex.value);
		myComponent.value = deptIndex.value === 'dept' ? AddUser :  Add;
		modalVisible.value = true;
		changeTitle.value = '新建';
	}else if(['leave', 'password'].includes(type)){
		myComponent.value = UserForm ;
		modalVisible.value = true;
		changeTitle.value = type =='leave' ?'离职' : '修改密码' ;
	}else if(type === 'back'){ // 返聘
		handleMixinSubmit(Api.ApiUserEnable, selectedKeys.value[0], getList, true, '返聘');
	}else if(type === 'resetPwd'){ // 重置密码
		handleMixinSubmit(Api.ApiResetPassword,{id:selectedKeys.value[0]},getList,true,'重置密码');
	}else if(['dept','post'].includes(type)){
		handleAdd(type)
	}else if(['deptManager', 'transfer'].includes(type)){
		changeTitle.value = 'dept'
		changeDeptPostRef.value.modalVisible = true ;
		changeDeptPostRef.value.deptCheckedIds = type === 'deptManager' ? leaderDeptIds : deptIds;
		// changeDeptPostRef.value.deptCheckedIds = [];
	}else if(type=='del'){
		const https = isDept ? Api.ApiUserDelete : Api.ApiPostDelete;
		handleMixinSubmit(https,{id:selectedKeys.value[0]},getList,true,'删除已勾选数据');
	}else if(type === 'search'){
		pageParams.searchKey = value;
		searchTag.value.keys = value;
		searchTag.value.title = '关键字';
		getList();
		comSearchRef.value.searchKey = '';
	}else if(['enable', 'disable'].includes(type)){
		const params = {
			id,
			name,
			remark,
			status: status ? 0 : 1,
		}
		handleMixinSubmit(Api.ApiPostUpdate, params , getList, true, status ? '启用' : '停用');
	}else if(['delUser'].includes(type)){ // 移除成员
		const res = await Api.ApiUserPost({ postId: id });
		postUserList.value = res || [];
		treeList.value = res || [];
		treeFilter.value = [];
		changeDeptPostRef.value.modalVisible = true;
	}else if(['addUser'].includes(type)){ // 添加成员
		treeList.value = postUserListAll.value;
		treeFilter.value = currentRowInfo.value?.userIds || [];
		changeDeptPostRef.value.modalVisible = true ;
	}else if(type === 'checkUser'){ // 查看部门下的用户
		deptIndex.value = 'dept';
		searchTag.value.keys = value.name;
		searchTag.value.title = '岗位';
		if(value?.totalUser > 0){
			injectCheckUser({ ...currentNodeInfo.value, postId: value.id, isCheck: true })
		}
	}else if(type === 'refreshList'){
		modalVisible.value = false;
		getList(); 
	}else if(type === 'tabs'){
		searchTag.value = {};
		pageParams.searchKey = '';
		pageParams.postId = '';
		currentNodeInfo.value.isDept = value === 'dept';
		getList();
	}else if(type === 'clearTag'){
		searchTag.value = {};
		injectCheckUser({ ...currentNodeInfo.value, postId: '', isCheck: true })
	}
}

const computedPinYin = computed(() => (str) => {
	pinyin.setOptions({ checkPolyphone: false, charCase: 2 });
	return str ? pinyin.getCamelChars(str).slice(0, 1) : '-';
})

onMounted(() => {
	document.addEventListener('click', handleDocumentClick);
	getPostUser();
});

onBeforeUnmount(() => {
	document.removeEventListener('click', handleDocumentClick);
})

// 监听鼠标点击是否是表格内
const handleDocumentClick = (event) => {
	const tableEl = tableRef?.value?.$el;
	nextTick(() => {
		const tableEl = tableRef?.value?.$el;
		if (tableEl && !tableEl.contains(event.target) && currentRow.value?.id && currentRowIndex.value > -1) {
			handleSubmit();
		}
	})
}

mitt.on('handleNode', row => {
	console.log('节点====', {...row});
	if(!row.isCheck){
		searchTag.value = {};
	}
	currentRowIndex.value = -1;
	pageParams.searchKey = '';
	if(row){
		currentNodeInfo.value = {
			...row,
			isDept: deptIndex.value === 'dept'
		};
		pageParams.deptId = row.id;
		pageParams.postId = row.isCheck ? row.postId : null;
		getList();
	}
})
defineExpose({
	handleBtn,
	dataList
})
</script>
<style lang="scss" scoped>
.table {
	&-tabs{
		margin-bottom: 10px;
		display: flex;
		align-items: center;
		justify-content: space-between;
		.right{
			.arco-tag{
				margin: 0 10px 0 6px;
			}
		}
	}
	.common-area{
		background: rgba(245, 245, 245, 1);
		padding: 4px 8px;
		// display: inline-block;
		// display: flex;
		// align-items: center;
		border-radius: 6px;
		font-size: 13px;
		i{
			background: rgba(235, 244, 255, 1);
			// margin-right: 5px;
			// display: inline-block;
			padding: 0 2px;
			border-radius: 4px;

		}
	}
	&-header {
		background: #f3f3f4;
		height: 42px;
		display: flex;
		justify-content:space-between;
		align-items: center
	}
	&-number {
		padding-left: 10px;
	}
	&-btn {
		margin:0 10px;
		color: #242323;
		cursor: pointer;
		&:hover {
			color: #165dff;
		}
		.EachApp {
			font-size: 14px;
			margin-right: 2px;
		}
	}
	&-list{
		height: calc(100% - 45px);
		overflow: auto;
	}
	.disable{
		color: #999;
		pointer-events: none;
		.disable-btn {
			cursor: not-allowed !important;
		}
	}
	.small-tag{
		padding-top: 1px;
	}
}
</style>
